import datetime
import os

import allure
import requests

from common.log.log import log

"""
爬虫——获取图片
"""


@allure.step('保存图片到本地目录')
def requests_save_img(img_url, save_dir, save_name):
    """
    提供图片url，保存图片到本地目录
    :param img_url:
    :param save_dir:
    :param save_name:
    :return:
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 '
                      '(KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36'
    }
    res = requests.get(img_url, headers=headers).content
    try:
        with open(save_dir + f'/{save_name}.jpg', 'wb') as f:
            log.info('保存图片')
            f.write(res)
    except OSError:
        with open(save_dir + f'/{save_name[5:]}.jpg', 'wb') as f:
            log.info('保存图片')
            f.write(res)


if __name__ == '__main__':
    # img_url = 'https://testerhome.com/uploads/user/avatar/53052/4cdc1b.png!md'
    img_url = 'https://testerhome.com/uploads/user/avatar/14570/535db9.jpg!md'
    name = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    save_dir = f"/\\"
    if os.path.exists(save_dir) == False:
        os.makedirs(save_dir)
    requests_save_img(img_url, save_dir, 'sdfsdf')
